import router from './router'
import store from './store/index'
import progress from 'nprogress'
import 'nprogress/nprogress.css'
import uas from 'uas-core-api'
import config from '@/config'
uas.server(config.authPath)
const checkPermission = (to, from, next) => {
    uas.checkLogin(async (res) => {
        if (res.id) {
            const userInfo = store.getters.userInfo
            if (userInfo && userInfo.id) {
                if (to.matched.length) {
                    next()
                } else {
                    next('/404')
                }
            } else {
                const { roles = [] } = await store.dispatch('user/getUserInfo')
                const accessRoutes = await store.dispatch(
                    'permission/generateRoutes',
                    roles
                )
                router.addRoutes(accessRoutes)
                await store.dispatch('permission/generateBtnsPermission', roles) // 按钮权限
                next({ ...to, replace: true })
            }
        } else {
            next(false)
            const url = encodeURIComponent(window.location.href)
            store.dispatch('app/setRedirectUrl', url)
            window.location.href = `${config.authPath}/uas/server?e=sso&url=${url}`
        }
    })
}

const checkPermissionByMock = async (to, from, next) => {
    const roles = store.getters.roles
    if (roles && roles.length) {
        if (to.matched.length) {
            next()
        } else {
            next('/404')
        }
    } else {
        const { roles = [] } = await store.dispatch('user/getUserInfoByMock')
        const accessRoutes = await store.dispatch(
            'permission/generateRoutes',
            roles
        )
        router.addRoutes(accessRoutes)
        await store.dispatch('permission/generateBtnsPermission', roles) // 按钮权限
        next({ ...to, replace: true })
    }
}

router.beforeEach((to, from, next) => {
    console.log('即将访问路由：' + (to.name || to.path))
    progress.start()
    if (config.authMock) {
        checkPermissionByMock(to, from, next).then(() => {})
    } else {
        checkPermission(to, from, next)
    }
})
router.afterEach(() => {
    progress.done()
})
